// pages/loginAndRegister/loginAndRegister.js
const API = require('../../common/constant.js');
const util = require('../../utils/util');
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isToEvent: false, //判断用户是否由分享进入
    pageState: '1',
    eventUserId: null,
    isChecked: false,
    isGetCode: false,
    sexPick: {
      array: ['男', '女'],
      index: 0,
      isSexPick: false
    },
    register: {
      nickname: '',
      sex: '',
      mobile: '',
      code: '',
      password: ''
    },
    codeStatus: '获取验证码',
    isLogin: false,
    isRegister: false
  },
  isAgree: function () {
    this.setData({
      isChecked: !this.data.isChecked
    })
  },
  changePageState: function (e) {
    var pageState = e.currentTarget.dataset.no
    this.setData({
      pageState: pageState
    })
  },
  sexPickerChange: function (e) {
    this.setData({
      ['sexPick.index']: e.detail.value,
      ['sexPick.isSexPick']: true,
      ['register.sex']: parseInt(e.detail.value) + 1 + ""
    })
  },
  regUsername: function (e) {
    this.setData({
      ['register.nickname']: e.detail.value
    })
  },
  regPhone: function (e) {
    this.setData({
      ['register.mobile']: e.detail.value
    })
  },
  regCode: function (e) {
    this.setData({
      ['register.code']: e.detail.value
    })
  },
  regPassword: function (e) {
    this.setData({
      ['register.password']: e.detail.value
    })
  },
  registerUser: function (e) {
    if (this.data.isRegister){
      return
    }
    let register = this.data.register;
    let state = true;
    let iptCode = this.data.iptCode;
    for (let name in register) {
      if (register[name].length === 0) {
        state = false;
      }
    }
    if (iptCode != register.code) {
      state = false;
      app.showUserInfo('验证码不正确', 'none', 2000)
      return
    }
    if (!this.data.isChecked) {
      wx.showToast({
        title: '请阅读并同意协议',
        icon: "none",
        duration: 2000
      })
    } else if (!state) {
      wx.showToast({
        title: '请正确填写信息',
        icon: "none",
        duration: 2000
      })
    } else {
      //注册
      this.setData({
        isRegister: true
      })
      this.register(this.data.register);
    }
  },

  getPhoneCode: function () {
    let phone = this.data.register.mobile;
    let isGetCode = this.data.isGetCode;
    let that = this;
    let timer = '';
    if (phone.length < 11) {
      app.showUserInfo("请正确输入手机号", "none", 2000)
      return;
    }
    if (isGetCode) {
      app.showUserInfo("一个手机60s内只能接收到一条验证码", "none", 2000);
      return
    }
    let mobile = phone + "";
    this.setData({
      isGetCode: true
    })
    timer = setTimeout(function () {
      that.setData({
        isGetCode: false
      })
    }, 60000);
    let nowtime = 60;
    let codetime = setInterval(() => {
      nowtime--;
      this.setData({
        codeStatus: nowtime + 's'
      });
      if (nowtime == 0) {
        this.setData({
          codeStatus: '获取验证码'
        });
        clearInterval(codetime);
      }
    }, 1000);
    util.http({
      url: API.URL.USER.FIND_MOBILECODE,
      data: {
        mobile: mobile
      },
      success: (res) => {
        this.setData({
          iptCode: res.data.bussData
        });

      },
      fail: (res) => {
        clearTimeout(timer)
        app.showUserInfo(res.msg, 'none', 1000)
        this.setData({
          isGetCode: false
        })
      }
    })
  },
  register: function (param) {
    let that = this;
    let isUserInfo = false;
    wx.getSetting({
      success: (res) => {
        isUserInfo = res.authSetting["scope.userInfo"];
      },
      complete: () => {
        if (!isUserInfo) {
          app.isGoToGetScope();
          return false
        }
        wx.showLoading({
          title: '正在注册'
        })
        util.http({
          url: API.URL.USER.REGISTER,
          data: {
            ...param
          },
          success: (res) => {
            console.log(res);
            wx.setStorageSync('userAccount', that.data.register.mobile);
            wx.setStorageSync('userPassword', that.data.register.password);
            wx.setStorageSync('sessionId', res.data.bussData.sessionId);
            wx.setStorageSync('userInfo',res.data.bussData);
            wx.hideLoading();
            wx.showLoading({
              title: '正在跳转'
            })
            app.login();
            if (that.data.isToEvent) {
              setTimeout(function () {
                wx.hideLoading();
                that.setData({
                  isRegister: false
                })
                wx.navigateTo({
                  url: `../FanInfo/FanInfo?id=${that.data.eventId}&isIndex=true`
                })
              }, 2000)
            } else {
              setTimeout(function () {
                wx.hideLoading();
                that.setData({
                  isRegister: false
                })
                wx.switchTab({
                  url: '/pages/index/index'
                })
              }, 2000)
            }
          },
          fail: (res) => {
            wx.hideLoading();
            that.setData({
              isRegister: false
            })
            console.log(res);
            app.showUserInfo(res.msg, "none", 1500);
          }
        })
      }
    })
  },
  getLoginPhone: function (e) {
    // console.log(e.detail.value);
    this.setData({
      loginPhone: e.detail.value
    })
  },
  getLoginPassword: function (e) {
    // console.log(e.detail.value);
    this.setData({
      loginPassword: e.detail.value
    })
  },

  loginAcc: function () {
    if (this.data.isLogin) {
      return
    }
    this.setData({
      isLogin: true
    })
    let phone = this.data.loginPhone;
    let password = this.data.loginPassword;
    this.testLoginInfo(phone, password)
  },
  testLoginInfo: function (phone, password) {
    let that = this;
    if (!(phone && password)) {
      app.showUserInfo("请输入账号和密码", "none", 2000)
      this.setData({
        isLogin: false
      })
      return false;
    }
    if (!this.testPhoneAndPassword(phone, password)) {
      this.setData({
        isLogin: false
      })
      return false;
    }
    let isUserInfo = false;
    wx.getSetting({
      success: (res) => {
        isUserInfo = res.authSetting["scope.userInfo"];
      },
      complete: () => {
        if (!isUserInfo) {
          app.isGoToGetScope();
          this.setData({
            isLogin: false
          })
          return false
        }
        wx.showLoading({
          title: '正在登录'
        })
        util.http({
          url: 'https://invitedinner.icebartech.com/api/mini/user/miniLogin',
          data: {
            mobile: phone,
            password: password
          },
          success: (res) => {
            console.log(res);
            wx.hideLoading();
            wx.setStorageSync('userAccount', that.data.loginPhone);
            wx.setStorageSync('userPassword', that.data.loginPassword);
            wx.showLoading({
              title: '正在跳转',
            })
            app.login();
            wx.setStorageSync("sessionId", res.data.bussData.sessionId);
            wx.setStorageSync('userInfo', res.data.bussData);
            if (that.data.isToEvent) {
              if (res.data.bussData.userId + '' === that.data.eventUserId + '') {
                setTimeout(function () {
                  wx.hideLoading();
                  that.setData({
                    isLogin: false
                  })
                  wx.navigateTo({
                    url: `../myPublishEventInfo/myPublishEventInfo?id=${that.data.eventId}&isIndex=true`
                  })
                }, 2000)
              } else {
                setTimeout(function () {
                  wx.hideLoading();
                  that.setData({
                    isLogin: false
                  })
                  wx.navigateTo({
                    url: `../FanInfo/FanInfo?id=${that.data.eventId}&isIndex=true`
                  })
                }, 2000)
              }
            } else {
              setTimeout(function () {
                wx.hideLoading();
                that.setData({
                  isLogin: false
                })
                wx.switchTab({
                  url: '/pages/index/index?isIndex=true'
                })
              }, 1500)
            }
          },
          fail: (res) => {
            that.setData({
              isLogin: false
            })
            console.log(res);
            app.showUserInfo(res.msg, "none", 1500)
          }
        })
      }
    })
  },
  testPhoneAndPassword: function (phone, password) {
    if (phone.length != 11) {
      app.showUserInfo("手机号格式不对", "none", 1000)

      return false;
    }
    if (password.length < 6) {
      app.showUserInfo("密码格式不对", "none", 1000)
      return false;
    }
    return true;
  },

  getUserInfo: function (e) {
    if (this.data.hasUserInfo) {
      return;
    }
    console.log("首页授权按钮", e)
    if (e.detail.errMsg === "getUserInfo:ok") {
      this.setData({
        hasUserInfo: true
      })
      app.globalData.hasUserInfo = true;
    }
    wx.showLoading({
      title: '正在加载'
    })
    let iv = e.detail.iv;
    let encryptedData = e.detail.encryptedData;
    wx.setStorageSync('wxUserInfo', e.detail.userInfo);
    let that = this;
    wx.login({
      success: res => {
        console.log('wx.login调用成功', res)
        let code = res.code;
        let params = {
          iv: iv,
          encryptedData: encryptedData
        }
        wx.request({
          url: API.URL.USER.MINI_WEIXINLOGIN,
          data: {
            code
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: "POST",
          success: res => {
            console.log('微信登陆接口调用成功', res)
            params.openId = res.data.data.bussData.openId;
            wx.setStorageSync("openId", params.openId)
            that.saveUserInfo(params);
            wx.hideLoading();
          },
          fail: (res) => {
            console.log('微信登陆接口调用失败', res)
            wx.hideLoading();
            app.showUserInfo(res.msg, "none", 1000)
          }
        })
      },
      fail: (res) => {
        console.log('wx.login调用失败', res);
        app.showUserInfo("保存用户信息失败", "none", 1000)
      }
    })
  },
  saveUserInfo: function (param) {
    let that = this;
    let url = API.URL.USER.SAVE_MINIUSERINFO;
    let local = app.getMyLocaltion();
    wx.request({
      url: 'https://invitedinner.icebartech.com/api/mini/user/saveMiniUserInfo',
      data: {
        openId: param.openId,
        encryptedData: param.encryptedData,
        iv: param.iv,
        longitude: local.longitude,
        latitude: local.latitude
      },
      method: "POST",
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: (data) => {
        console.log('保存用户信息成功', data);
      },
      fail: (res) => {
        console.log('保存用户信息失败', res)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (wx.getStorageSync('wxUserInfo')) {
      this.setData({
        hasUserInfo: true
      })
    } else {
      this.setData({
        hasUserInfo: false
      })
    }
    let loginPhone = wx.getStorageSync('userAccount');
    let loginPassword = wx.getStorageSync('userPassword');
    this.setData({
      loginPhone: loginPhone,
      loginPassword: loginPassword
    })
    let that = this;
    let id = options.id || false;
    let eventUserId = options.eventUserId + '' || false;
    if (id && eventUserId) {
      this.setData({
        isToEvent: true,
        eventId: id,
        eventUserId: eventUserId
      })
      if (wx.getStorageSync('sessionId')) {
        let userId = wx.getStorageSync('userInfo').userId + '';
        console.log('eventUserId为:' + eventUserId, '本人id为:' + userId)
        if (eventUserId === userId) {
          app.showUserInfo(`你已登录，2s后自动跳转`, 'none', 2000)
          setTimeout(function () {
            wx.navigateTo({
              url: `../myPublishEventInfo/myPublishEventInfo?id=${that.data.eventId}&isIndex=true`
            });
          }, 2000)
        } else {
          app.showUserInfo(`你已登录，2s后自动跳转`, 'none', 2000)
          setTimeout(function () {
            wx.navigateTo({
              url: `../FanInfo/FanInfo?id=${that.data.eventId}&isIndex=true`
            });
          }, 2000)
        }
      }
    }
  }
})